package com.woniuxy.service.impl;

import com.woniuxy.dao.LoginAuthDao;
import com.woniuxy.entity.RbacManager;
import com.woniuxy.entity.ResponseEntity;
import com.woniuxy.service.LoginAuthService;
import com.woniuxy.shiro.jwt.JWTUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 马宇航
 * @Do: 实现类
 * @DateTime: 22/05/23/0023 上午 10:35
 * @Component: 成都蜗牛学苑
 **/
@Service
public class LoginAuthServiceImpl implements LoginAuthService {
    LoginAuthDao loginAuthDao;
    @Autowired(required = false)
    public LoginAuthServiceImpl(LoginAuthDao loginAuthDao) {
        this.loginAuthDao = loginAuthDao;
    }
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public ResponseEntity login(String username, String password) {
        SimpleHash simpleHash = new SimpleHash("MD5", password, username);
        String newPassword = simpleHash.toHex();
        RbacManager rbacManager = loginAuthDao.login(username,newPassword);
        String account = rbacManager.getAccount();
        String password1 = rbacManager.getPassword();
        //调用jwt工具类生成token
        String token = JWTUtils.sign(account, password1);
        //把token当做key，返回的对象当做值，存入redis中
        redisTemplate.opsForValue().set(token,rbacManager);
//       设置这个token的过期时间
        redisTemplate.expire(token,30, TimeUnit.MINUTES);
        ResponseEntity responseEntity = new ResponseEntity(rbacManager);
        responseEntity.putKey("token",token);
        return responseEntity;
    }

    @Override
    public RbacManager findByName(String userName) {
       return loginAuthDao.findByName(userName);
    }

    @Override
    public Set<String> findRolesByName(String username) {
        return loginAuthDao.findRoles(username);
    }

    @Override
    public Set<String> findPermsByName(String username) {
        return loginAuthDao.findPermsByName(username);
    }
}
